<template>
  <div id="iframe">
    <el-row :gutter="20" class="fixed">
      <el-col :span="3"><el-button>操作说明</el-button></el-col>
      <el-col :span="8"><el-input type="text" disabled v-model="url"></el-input></el-col>
      <el-col :span="7"><div class="num">已选链接数：<span id="num">{{ num }}</span></div></el-col>
      <el-col :span="3"><el-button @click="grabTest">抓取测试</el-button></el-col>
      <el-col :span="3"><el-button type="primary" @click="getElemnt">确定</el-button></el-col>
    </el-row>
    <el-dialog title="提示" :visible.sync="dialogVisible" width="30%" append-to-body>
      <div>测试抓取到{{ num }}个链接</div>
      <div class="links" v-for="(item,index) in ruleList" :key="index">{{ item.url }}</div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>
    <!-- <div id="myIframe" ref="myIframe" v-html="htmlData" @click="handleClick"></div> -->
    <iframe id="myIframe" ref="myIframe" frameborder="0" allowfullscreen :srcdoc="htmlData" security="restricted" allow="same-origin" sandbox="allow-same-origin allow-scripts" :src="url" @load="extractLinks" @mouseover="highlightText"></iframe>
  </div>
</template>

<script>
import $ from "jquery";
export default {
  props: {
    url: {
      type: String,
      default: ''
    },
    htmlData: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      dialogVisible: false,
      ruleList: [], // 获取链接
      num: 0, // 获取链接个数
      urlHtml: ''
    }
  },
  watch: {
    htmlData(newData) {
    }
  },
  // mixins: [preventLinkClickMixin],
  mounted() {

  },
  updated() {
    // console.log(document.getElementsByClassName('ntes-nav'))
    // document.getElementsByClassName('ntes-nav')[0].style.position = 'relative'
  },
  methods: {
    handleClick(event) {
      event.preventDefault();
      // 获取点击的元素
      const clickedElement = event.target
      if (clickedElement.classList.contains('highlight')) {
        clickedElement.classList.remove('highlight');
        clickedElement.style.backgroundColor = ''
      } else {
        clickedElement.classList.add('highlight');
        clickedElement.style.backgroundColor = 'yellow'
      }
      // 获取层级路径并显示
      const path = this.getElementPath(clickedElement);
      console.log('1111',path);
    },
    getElementPath(element) {
      let path = ''
      while (element) {
        console.log(element.id)
        let tagName = ''
        if (element.tagName&&element.tagName.toLowerCase()&&element.id!=='myIframe') {
          tagName = element.tagName.toLowerCase()
        } else {
          break
        }
        if (element.parentNode&&element.parentNode.children) {
          const index = Array.from(element.parentNode.children).indexOf(element)
          path = `${tagName}:nth-child(${index + 1})>${path}`
          element = element.parentNode
        } else {
          break
        }
      }
      return path;
    },
    grabTest() {
      this.dialogVisible= true
    //   this.getElemnt()
    },
    getElemnt() {
      // console.log(document.getElementsByClassName('highlight'))
      this.ruleList = []
      let element = document.getElementsByClassName('highlight')
      for (const item of element) {
        console.log(item.innerText)
        this.ruleList.push({
          title: item.innerText,
          url: item.href
        })
      }
      this.num = this.ruleList.length
      this.$emit('submitData',this,this.ruleList)
    },
    extractLinks: function () {
        const iframe = this.$refs.myIframe.contentDocument || this.$refs.myIframe.contentWindow.document
        // const aTag = iframe.querySelector('a');
        // if (aTag) {
        //     console.log(aTag); // 获取a标签的内容
        // }
        if (iframe) {
            const doc = iframe;
            // 确保iframe的内容已加载完成
            if (doc.readyState === 'complete') { }
            console.log('querySelectorAll', doc, doc.readyState)
        }
        const styleElement = document.createElement('style');
        styleElement.textContent = `
            .iframe_hover_bg{
                outline: solid 1px red !important;
                background-color: rgba(235,13,13,0.2) !important;
                cursor: pointer !important;
            }
            .iframe_hover_bg2{
                outline: solid 1px green !important;
                background-color: rgba(91,191,90,0.2) !important;
                cursor: pointer !important;
            }
            .iframe_hover_bg3{
                outline: solid 2px green !important;
                background-color: rgba(91,191,90,0.2) !important;
                cursor: pointer !important;
            }
            .fullscreen_alert{
                width: 100%;
                height: 100%;
                background-color: rgba(0, 0, 0, 0.5);
                position: fixed;
                top: 0;
                right: 0;
                bottom: 0;
                left: 0;
                z-index: 2147483647;
                color: #555;
                text-align: left;
                font-family: 'Helvetica Neue', 'STHeiti', '微软雅黑', 'Microsoft YaHei', Helvetica, Arial, sans-serif;
                display: none;
            }
            .ucy_dialog {
                width: 400px;
                background-color: #fff;
                border-radius: 4px;
                margin: 20px auto;
            }
            .header_title{
                display: flex;
                justify-content: space-between;
                border-bottom: solid 1px #ccc;
                font-size: 14px;
                line-height: 12px;
                padding: 16px 20px;
                color: #555;
            }
            .msg-content{
                box-sizing: border-box;
                width: 360px;
                margin: 10px 20px;
                background-color: #fff;
                overflow: auto;
                border-radius: 4px;
                display: block;
                padding: 10px;
                font-size: 13px;
                line-height: 1.42857143;
                color: #555;
                word-break: break-all;
                word-wrap: break-word;
                border: 1px solid #ccc;
                max-height: 300px;
            }
            .msg-footer{
                text-align:center;
                padding: 20px 0 10px 0;
            }
            .msg-btn{
                background-color: #1890ff;
                outline: none;
                border: #1890ff;
                color: #fff;
                width: 70px;
                line-height: 30px;
                border-radius: 6px;
                cursor:pointer
            }
            .msg-btn:hover{
                background-color: rgba(24, 144, 255,0.9);
                color: #fff;
            }
            .close-dialog:hover {
               color: rgba(0,0,0,0.5)
            }
            /* 添加更多样式 */
        `;
        iframe.head.appendChild(styleElement);
        // 在iframe的document中插入对话框的HTML
        const dialogHTML = `
            <div class="fullscreen_alert">
                <div class="ucy_dialog">
                    <div class="header_title">
                        <div>提示信息</div>
                        <span onclick="closeDialog()" class="close-dialog" style="cursor:pointer">×</span>
                    </div>
                    <pre class="msg-content">这不是一个有效链接，无法选中。</pre>
                    <div class="msg-footer"><button onclick="closeDialog()" class="msg-btn close-dialog">关闭</button></div>
                </div>
            </div>
        `;
        // 在这个元素的末尾插入了新的 HTML 字符串
        iframe.body.insertAdjacentHTML('beforeend', dialogHTML);

        // 在iframe的window中添加关闭对话框的函数
        const closeDialogScript = `
            function closeDialog() {
                ${iframe.querySelector('.fullscreen_alert').style.display = 'none'}
            }
        `;
        // 创建script并添加内容
        const script = iframe.createElement('script');
        script.textContent = closeDialogScript;
        iframe.body.appendChild(script);

        iframe.addEventListener('mouseover', this.handleMouseover); //鼠标悬浮
        iframe.addEventListener('mouseout', this.handleMouseout); // 鼠标离开
        iframe.addEventListener('click', this.handleClick); // 点击事件
    },
    // 鼠标悬浮
    handleMouseover(event) {
        const iframe = this.$refs.myIframe
        const target = event.target;
        console.log('88888mouseover', event, target.tagName)
        const fullscreen_alert = iframe.contentWindow.document.querySelector('.fullscreen_alert').style.display
        // 判断弹窗是否显示状态，显示就不改变区域外样式
        if (fullscreen_alert == 'none') {
            if (target.tagName == 'A' && target.href && target.href.indexOf('javascript:') == -1) {
                 // 判断当前标签是否是A标签
                // target.style.border = 'solid 1px green';
                target.classList.add("iframe_hover_bg2")
            } else if (target.parentNode && target.parentNode.href && target.parentNode.href.indexOf('javascript:') == -1) {
                // 判断父标签是否是A标签
                target.classList.add("iframe_hover_bg2")
            } else {
                target.classList.add("iframe_hover_bg")
            }
        }
        // 调用iframe内的函数来处理高亮逻辑
        // iframe.contentWindow.postMessage({
        //     action: 'highlight',
        //     selector: event.target.tagName === 'A' ? 'a' : 'a'
        // }, '*')
    },
    // 鼠标离开
    handleMouseout: function(event) {
        const target = event.target;
        // 删除你想要的样式
        target.classList.remove("iframe_hover_bg")
        target.classList.remove("iframe_hover_bg2")
    },
    // 点击事件
    handleClick: function (event) {
        event.preventDefault()
        event.stopPropagation()
        const target = event.target
        const iframe = this.$refs.myIframe
        console.log('2222222233click', target);
        // 获取iframe的内容document
        const iframeDocument = $('#myIframe').contents();
        if (target.tagName == 'A' && target.href && target.href.indexOf('javascript:') == -1) {
            // 先判断当前标签是否是A标签
            const hasClass = target.classList.contains('iframe_hover_bg3')
            if (hasClass) {
                console.log('类存在');
                target.classList.remove("iframe_hover_bg3")
                // 在iframe的document中删除一个属性
                iframeDocument.find('.iframe_hover_bg3').attr('data-selector', '');
            } else {
                console.log('类不存在');
                target.classList.add("iframe_hover_bg3")
                // 在iframe的document中添加一个属性
                iframeDocument.find('.iframe_hover_bg3').attr('data-selector', 'iframe_hover_bg3');
            }
        } else if (target.parentNode && target.parentNode.href && target.parentNode.href.indexOf('javascript:') == -1 && target.parentNode.tagName == 'A') {
            // 再判断父标签是否是A标签
            const hasClassParent = target.parentNode.classList.contains('iframe_hover_bg3')
            if (hasClassParent) {
                target.parentNode.classList.remove("iframe_hover_bg3")
                // 在iframe的document中删除一个属性
                iframeDocument.find('.iframe_hover_bg3').attr('data-selector', '');
            } else {
                target.parentNode.classList.add("iframe_hover_bg3")
                // 在iframe的document中添加一个属性
                iframeDocument.find('.iframe_hover_bg3').attr('data-selector', 'iframe_hover_bg3');
            }
        } else {
            // 若不是链接A标签，弹出提示内容
            const fullscreen_alert = iframe.contentWindow.document.querySelector('.fullscreen_alert').style.display
            if (fullscreen_alert == 'none') {
                iframe.contentWindow.document.querySelector('.fullscreen_alert').style.display = 'block'
            } else {
                //检查元素的class属性，是否包含特定的类名返回true/false
                if (target.classList.contains('close-dialog')) {
                    iframe.contentWindow.document.querySelector('.fullscreen_alert').style.display = 'none'
                }
            }
        }
        let selector = [] // 获取选中链接数组
        let urls = []
        // 获取iframe的body的自定义属性值
        const customAttributeValue = iframeDocument.find('.iframe_hover_bg3').attr('data-selector');
        // 获取自定义类名的数组并获取链接url
        iframeDocument.find('.iframe_hover_bg3').toArray().forEach(item => {
            console.log('item3333333', item)
            selector.push({
                title: item.innerText,
                url: item.href
            })
        })
        this.ruleList = selector
        this.num = this.ruleList.length
        // this.$emit('submitData',this,this.ruleList)
        console.log('selector222', selector,this.ruleList)
    },
    highlightText() {
        console.log('3333444444', document.getElementById('myIframe').contentWindow)
    },
  }
}
</script>
<style scoped lang="scss">
#iframe {
  width: 100%;
  height: 75vh;
  overflow-y: auto;
  position: relative;
  iframe{
    width: 100%;
    height: 100%;
    .highlight {
      background-color: yellow !important; /* 高亮背景色 */
      color: black; /* 高亮文字颜色 */
    }
  }
  .fixed {
    width: 100%;
    height: 36px;
    background-color: #fff;
    z-index: 99999;
    position: sticky;
    top: 0;
    left: 0;
    display: flex;
    .num {
      height: 36px;
      line-height: 36px;
      background-color: #eee;
      padding: 0 15px;
      border: 1px solid #ccc;
      border-radius: 3px;
    }
  }
  .highlight {
    background-color: yellow;
  }
}
  .links{
    line-height: 30px;
  }
</style>